import com.codezen.component.videoplayer.subs.SubtitleParser;

import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.filesystem.File;

import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.controls.sliderClasses.Slider;
import mx.controls.sliderClasses.SliderThumb;
import mx.events.DragEvent;
import mx.events.ListEvent;
import mx.managers.CursorManager;
import mx.managers.CursorManagerPriority;
import mx.styles.IStyleManager2;
import mx.styles.StyleManager;
import mx.utils.ObjectUtil;

import spark.components.List;
import spark.components.supportClasses.SliderBase;

import utils.anime.AniEpisode;
import utils.serials.Episode;

private var cursorID:int;
private var currentEpisodNum:int;

private function doLogout():void{
	//login = '';
	pass = '';
	save();
	currentState = "Login";
	//this.exit();
}


private function doLogin():void{
	// save login-pass data
	login = login_input.text;
	pass = pass_input.text;
	
	// save data to file
	if(save_creds.selected)
		save();
	
	// try loggin in
	tryLogin();
}

private function doLoginOffline():void{
	isOffline = true;
	tryLogin(isOffline);
}

private function dividerCreationComplete(e:Event):void{
	// set divider
	newsDivider.getDividerAt(0).x = (divider_pos/1000) * newsDivider.width;
}

private function onDividerDrag(e:Event):void{
	var x:int = newsDivider.getDividerAt(0).x; 
	divider_pos = int( (x/newsDivider.width) * 1000 );
	save();
}

private function onSeriesClick(e:MouseEvent):void{
	if(e.currentTarget.selectedItem == null) return;
	
	// write series ID
	var sid:String = e.currentTarget.selectedItem.id;
	
	// change state 
	currentState = "Series";
	
	// set img and description
	series_big_img.source = e.currentTarget.selectedItem.bimg;
	series_name_text.text = e.currentTarget.selectedItem.title;
	series_descr_text.htmlText  = e.currentTarget.selectedItem.info;
	
	// load data
	if(e.currentTarget.selectedItem.hasOwnProperty("original")){	
		loadSeries(sid);
	}else{
		loadAnime(sid);
	}
	
	// deselect
	e.currentTarget.selectedIndex = -1;	
}

private function filterAniSeasons(e:ListEvent):void{
	// write season num
	showSeason = String(seasons_combobox.selectedItem.season);
	
	// filter
	episodesList.filterFunction = filterBySeasonflashFilter;
	
	// refresh
	episodesList.refresh();
	
	// load eps from db
	dbAniLoadEpisodes();
}

private function filterSeasons(e:ListEvent):void{
	// write season num
	showSeason = String(seasons_combobox.selectedItem.season);
	
	// filter
	episodesList.filterFunction = filterBySeasonflashFilter;
	
	// refresh
	episodesList.refresh();
	
	// load eps from db
	dbLoadEpisodes();
}

private function filterBySeasonflashFilter(obj:Object):Boolean{
	return obj.season == showSeason;
}


private function onVideoClick(e:MouseEvent):void{
	// indus check for thumb press
	// @todo: do it normal way ~_~
	if(e.target.toString().indexOf("thumb") != -1) return;
	
	var list:List = e.currentTarget as List;
	
	if(list.selectedIndex == -1) return;
	
	// set current episode
	currentEpisodNum = list.selectedIndex; 
	
	// vars
	var simg:String;
	var txt:String;
	var video_link:String;
	var subs:Array = new Array();
	var ani:Boolean;
	
	// save old state
	if(currentState != "Player"){
		oldState = currentState;
	}
	
	// get links
	if( list.selectedItem.hasOwnProperty("serial_original") ){ // list.id == "new_ep_list" || list.id == "saved_ep_list"
		currentEpisode = list.selectedItem as Episode;
	
		txt = currentEpisode.serial_title +"\n";
		txt += currentEpisode.title;
		txt += " (сезон "+currentEpisode.season;
		txt += ", эпизод "+currentEpisode.num+")";
	
		// get video link
		video_link = currentEpisode.video;
		if(video_link.indexOf("[[local=") > 0){
			video_link = video_link.substring( video_link.indexOf("[[local=")+8, video_link.length-2 );
		}
		
		if(currentEpisode.sub == "1"){
			subs.push(video_link+".srt");
		}
		
		simg = currentEpisode.serial_simg;
	}else{
		currentAniEpisode = list.selectedItem as AniEpisode;
		ani = true;
		
		txt = currentAniEpisode.serial_title +"\n";
		txt += currentAniEpisode.title;
		txt += " (сезон "+currentAniEpisode.season;
		txt += ", эпизод "+currentAniEpisode.num+")";
		
		// get video link
		video_link = currentAniEpisode.video;
		if(video_link.indexOf("[[local=") > 0){
			video_link = video_link.substring( video_link.indexOf("[[local=")+8, video_link.length-2 );
			subs.push( video_link.replace(".mp4", ".srt") ); 
		}
		
		simg = currentAniEpisode.serial_simg;
		
		if(subs.length == 0){
			if(currentAniEpisode.sub1 == '1'){
				// http://anime.tulavideo.net/4/01-05_1.srt
				subs.push("http://anime.tulavideo.net/"+currentAniEpisode.serial_id+"/"+currentAniEpisode.aid+"_1.srt");
			}
			if(currentAniEpisode.sub2 == '1'){
				subs.push("http://anime.tulavideo.net/"+currentAniEpisode.serial_id+"/"+currentAniEpisode.aid+"_2.srt");
			}
		}
	}
	
	currentState = "Player";
	videoPlayer.video_title.text = txt;
	videoPlayer.video_pic.source = simg;
	
	// fill eps
	if(list == series_video_list){
		playerEpisodesFill(ani);
	}
	
	// clean
	list = null;
	
	// load and play
	videoPlayer.loadVideoAndPlay(video_link, subs);
}

private function playerEpisodesFill(anime:Boolean):void{
	if(anime){
		var aniEp:AniEpisode;
		
		// prev episode
		if(currentEpisodNum + 1 < series_video_list.dataProvider.length){
			aniEp = series_video_list.dataProvider.getItemAt(currentEpisodNum + 1) as AniEpisode;
			videoPlayer.player_prev_ep_img.source = aniEp.image;
			videoPlayer.player_prev_ep_txt.text = aniEp.title;
		}else{
			videoPlayer.player_prev_ep_txt.text = "null";
		}
		
		// next episode
		if(currentEpisodNum - 1 > -1){
			aniEp = series_video_list.dataProvider.getItemAt(currentEpisodNum - 1) as AniEpisode;
			videoPlayer.player_next_ep_img.source = aniEp.image;
			videoPlayer.player_next_ep_txt.text = aniEp.title;
		}else{
			videoPlayer.player_next_ep_txt.text = "null";
		}
		
		// clean
		aniEp = null;
	}else{
		var ep:Episode;
		
		// prev episode
		if(currentEpisodNum + 1 < series_video_list.dataProvider.length){
			ep = series_video_list.dataProvider.getItemAt(currentEpisodNum + 1) as Episode;
			videoPlayer.player_prev_ep_img.source = ep.image;
			videoPlayer.player_prev_ep_txt.text = ep.title;
		}else{
			videoPlayer.player_prev_ep_txt.text = "null";
		}
		
		// next episode
		if(currentEpisodNum - 1 > -1){
			ep = series_video_list.dataProvider.getItemAt(currentEpisodNum - 1) as Episode;
			videoPlayer.player_next_ep_img.source = ep.image;
			videoPlayer.player_next_ep_txt.text = ep.title;
		}else{
			videoPlayer.player_next_ep_txt.text = "null";
		}
		
		// clean
		ep = null;
	}
}


private function prevEpisode():void{
	// play prev
	currentEpisodNum += 1;
	series_video_list.selectedIndex = currentEpisodNum;
	series_video_list.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
}

private function nextEpisode():void{
	// play prev
	currentEpisodNum -= 1;
	series_video_list.selectedIndex = currentEpisodNum;
	series_video_list.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
}

private function backToSeries():void{
	// change state
	currentState = oldState;
}

private function onFilterKey(e:KeyboardEvent):void{
	var data:ArrayCollection = series_list.dataProvider as ArrayCollection;
	
	if(data == null) return;
	if(filter_input.text.length > 0){
		var name:String;
		data.filterFunction = function(item:Object):Boolean{
			name = item.title;
			name = name.toLowerCase();
			return name.indexOf(filter_input.text) > -1;
			//return true;
		};
	}else{
		data.filterFunction = null;
	}
	data.refresh();
}

private function onSeriesSortChange(e:Event):void{
	var option:String = series_sort.selectedItem.data;
	var data:ArrayCollection = series_list.dataProvider as ArrayCollection;
	
	var sort:Sort = new Sort();
	
	switch(option){
		case "num":		
			sort.fields = [new SortField("id", false, true, true)];
			break;
		case "name":
			sort.fields = [new SortField("title")];
			break;
	}
	
	data.sort = sort;
	data.refresh();
}

private function onAniFilterKey(e:KeyboardEvent):void{
	var data:ArrayCollection = anime_list.dataProvider as ArrayCollection;
	
	if(data == null) return;
	if(ani_filter_input.text.length > 0){
		var name:String;
		data.filterFunction = function(item:Object):Boolean{
			name = item.title;
			name = name.toLowerCase();
			return name.indexOf(ani_filter_input.text) > -1;
			//return true;
		};
	}else{
		data.filterFunction = null;
	}
	data.refresh();
}

private function onAnimeSortChange(e:Event):void{
	var option:String = anime_sort.selectedItem.data;
	var data:ArrayCollection = anime_list.dataProvider as ArrayCollection;
	
	var sort:Sort = new Sort();
	
	switch(option){
		case "num":		
			sort.fields = [new SortField("id", false, true, true)];
			break;
		case "name":
			sort.fields = [new SortField("title")];
			break;
	}
	
	data.sort = sort;
	data.refresh();
}

/**
 * Draw episode list menu
 * 
 * @param e
 */
private function popUpMenuEpisodeList(e:MouseEvent):void{
	if(currentEpisode == null && currentAniEpisode == null) return;
	
	// get ac
	var dp:ArrayCollection = e.currentTarget.dataProvider as ArrayCollection;
	
	//e.currentTarget.selectedItem = e.target;
	//trace( e.currentTarget );
	
	// new menu
	var root:NativeMenu = new NativeMenu();
	
	var wachedSelected:NativeMenuItem = new NativeMenuItem("Я это смотрел.");
	wachedSelected.addEventListener(Event.SELECT, function(e:Event):void{
		if(currentEpisode != null){
			setEpisodeWatched(currentEpisode);
		}
		if(currentAniEpisode != null){
			setAniEpisodeWatched(currentAniEpisode);
		}
	});
	root.addItem(wachedSelected);
	
	/*var separateSub2:NativeMenuItem = new NativeMenuItem("-", true);
	root.addItem(separateSub2);*/
	
	var notWachedSelected:NativeMenuItem = new NativeMenuItem("Я не видел!");
	notWachedSelected.addEventListener(Event.SELECT, function(e:Event):void{
		if(currentEpisode != null){
			setEpisodeNotWatched(currentEpisode);
		}
		if(currentAniEpisode != null){
			setAniEpisodeNotWatched(currentAniEpisode);
		}
	});
	root.addItem(notWachedSelected);
	
	if(currentState == "Series"){
		var separateSub:NativeMenuItem = new NativeMenuItem("-", true);
		root.addItem(separateSub);
		
		var wachedAllSelected:NativeMenuItem = new NativeMenuItem("Я видел весь сезон!");
		wachedAllSelected.addEventListener(Event.SELECT, function(e:Event):void{
			if(currentEpisode != null){
				setSeasonWatched();
			}
			if(currentAniEpisode != null){
				setAniSeasonWatched();
			}
		});
		root.addItem(wachedAllSelected);
		var notWachedAllSelected:NativeMenuItem = new NativeMenuItem("Я не видел этот сезон.");
		notWachedAllSelected.addEventListener(Event.SELECT, function(e:Event):void{
			if(currentEpisode != null){
				setSeasonNotWatched();
			}
			if(currentAniEpisode != null){
				setAniSeasonNotWatched();
			}
		});
		root.addItem(notWachedAllSelected);
	}
	
	var separateSub2:NativeMenuItem = new NativeMenuItem("-", true);
	root.addItem(separateSub2);
	
	// if not saved list
	var cacheEpSelected:NativeMenuItem;
	if(e.currentTarget != saved_ep_list){
		cacheEpSelected = new NativeMenuItem("Сохранить для просмотра");
		cacheEpSelected.addEventListener(Event.SELECT, function(e:Event):void{
			if(currentEpisode != null){
				cacheEpisode(currentEpisode);
			}
			if(currentAniEpisode != null){
				cacheAniEpisode(currentAniEpisode);
			}
		});
		root.addItem(cacheEpSelected);
	}else{
		cacheEpSelected = new NativeMenuItem("Удалить");
		cacheEpSelected.addEventListener(Event.SELECT, function(e:Event):void{
			if(currentEpisode != null){
				delCachedEpisode(currentEpisode);
			}
			if(currentAniEpisode != null){
				delAniCachedEpisode(currentAniEpisode);
			}
		});
		root.addItem(cacheEpSelected);
	}
	
	// assign native menu
	root.display(stage, e.stageX - 75, e.stageY);
}

/**
 * Draw series list menu
 * 
 * @param e
 */
private function popUpMenuSeriesList(e:MouseEvent):void{
	if(currentSeries == null && currentAniSeries == null) return;
	
	// get ac
	var dp:ArrayCollection = e.currentTarget.dataProvider as ArrayCollection;
	
	//e.currentTarget.selectedItem = e.target;
	//trace( e.currentTarget );
	
	// new menu
	var root:NativeMenu = new NativeMenu();
	
	var deleteSelected:NativeMenuItem = new NativeMenuItem("Удалить");
	deleteSelected.addEventListener(Event.SELECT, function(e:Event):void{
		if(currentSeries != null){
			dbRemoveSeries();
		}
		if(currentAniSeries != null){
			dbRemoveAniSeries();
		}
	});
	root.addItem(deleteSelected);
	
	// assign native menu
	root.display(stage, e.stageX - 75, e.stageY);
}

private function setVideoWatched():void{
	if(currentEpisode != null){
		setEpisodeWatched(currentEpisode);
	}
	if(currentAniEpisode != null){
		setAniEpisodeWatched(currentAniEpisode);
	}
}

/**
 * Sets high priority busy cursor 
 */
private function setBusyCursor():void{
	CursorManager.setBusyCursor();
}

/**CursorManager.removeCursor(cursorID);
 * Sets high priority busy cursor 
 */
private function removeBusyCursor():void{
	CursorManager.removeBusyCursor();
}
